package com.wzt.lianfirecontrol.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.mob.pushsdk.MobPush;
import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.utils.AndroidFileUtil;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.FileUtil;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.WebViewSettingUtils;
import com.wzt.lianfirecontrol.view.GetTopWebView;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 显示网页（备用）
 */
public class WebActivity extends BaseActivity implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {

    private View include_head_title;
    private TextView tv_title;
    private SuperSwipeRefreshLayout swipeLayout;
    private WebView webview;
    private WebChromeClient webChromeClient;
    private Bundle bundle;
    private String url;
    // 上传图片弹出菜单
    private PopupWindow popupWindow;

    // 打开图片标记
    private final int IMAGE_OPEN = 1;
    private final int PHOTO_OPEN = 2;
    private Uri photoUri;

    private final static int SUBMIT_IMAGE_WHAT = 0;

    private String faultId;

    private View include_progress_bar;
    private Dialog checkDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bundle = getIntent().getExtras();
        if (null != bundle) {
            url = bundle.getString("url");
        }
        setContentView(R.layout.a_web);
        setImmerseLayout(findViewById(R.id.include_head_title), findViewById(R.id.rl_head_content));
        initView();
    }

    private void initView() {
        initHeadView();
        swipeLayout = (SuperSwipeRefreshLayout) findViewById(R.id.swipe_container);
        swipeLayout.setOnSwipeRefreshListener(this);
        webview = (GetTopWebView) findViewById(R.id.gtwv_web);
        if (url.contains("needRefresh=0")) {
            swipeLayout.setEnabled(false);
            ((GetTopWebView) webview).setNeedRefresh(false);
        } else {
            InitView.instance().initSuperSwipeLayout(swipeLayout);
        }
        webview.setVerticalScrollbarOverlay(false);
        ((GetTopWebView) webview).setSwipeRefreshLayout(swipeLayout);
        webview.setOverScrollMode(View.OVER_SCROLL_ALWAYS);

        initWebView();

        if (!StringUtils.isEmpty(url)) {
            webview.loadUrl(url);
        }

        include_progress_bar = findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(this, include_progress_bar);

    }

    private void initHeadView() {
        include_head_title = findViewById(R.id.include_head_title);
        tv_title = findViewById(R.id.tv_title);
        findViewById(R.id.iv_back).setVisibility(View.VISIBLE);
    }

    /**
     * 初始化webview
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        webview = WebViewSettingUtils.getSettingInstance(webview, this);
        webChromeClient = new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                swipeLayout.setRefreshing(false);
                tv_title.setText(title);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                return super.onJsAlert(view, url, message, result);
            }
        };
        webview.setWebChromeClient(webChromeClient);
        WebViewClient webViewClient = new BridgeWebViewClient((BridgeWebView) webview) {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.e("startUrl", url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log.e("shouldOverrideUrl", url);
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.e("finishUrl", url);
            }
        };
        webview.setWebViewClient(webViewClient);

     //   setJsBridge();
    }

    private void setJsBridge() {
        if (webview instanceof GetTopWebView) {

            //注册showToast方法
            ((GetTopWebView) webview).registerHandler("showToast", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    if (StringUtils.isEmpty(data)) {
                        function.onCallBack("数据不能为空");
                        return;
                    }
                    ToastUtils.showToast(WebActivity.this, data);
                    function.onCallBack("toast成功");
                }
            });

            //注册submit picture方法
            ((GetTopWebView) webview).registerHandler("submitPic", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        faultId = data;
                        initSubmitPicView();
                    } catch (Exception e) {
                        function.onCallBack(" 返回值错误");
                    }
                }
            });

            //返回
            ((GetTopWebView) webview).registerHandler("doBack", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        if (null != webview && webview.canGoBack()) {
                            webview.goBack();
                        }
                        function.onCallBack(" 返回成功");
                    } catch (Exception e) {
                        function.onCallBack(" 返回失败");
                    }
                }
            });

            //注册关闭网页方法
            ((GetTopWebView) webview).registerHandler("closeWeb", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        WebActivity.this.finish();
                    } catch (Exception e) {
                        function.onCallBack(" 返回失败");
                    }
                }
            });
            //注册修改preference值方法
            ((GetTopWebView) webview).registerHandler("changePreference", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        if (!StringUtils.isEmpty(data)) {
                            String[] keyValue = data.split(",");
                            PreferencesUtils.putString(WebActivity.this, keyValue[0], keyValue[1]);
                            function.onCallBack(" 修改成功");
                        } else {
                            function.onCallBack(" data不能为空");
                        }
                    } catch (Exception e) {
                        function.onCallBack(" 修改失败");
                    }
                }
            });
            //注册退出登录方法
            ((GetTopWebView) webview).registerHandler("exitAccount", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        UserInfoModel.clearUserLoginMessage(WebActivity.this);
                        ActivityCollecter.finishAllActivitys();
                        Bundle bundle1 = new Bundle();
                        if (!StringUtils.isEmpty(data)) {
                            bundle1.putString("error_msg", data);
                        }
                        openActivity(LoginActivity.class, bundle1, 0);
                        function.onCallBack(" 退出成功");
                    } catch (Exception e) {
                        function.onCallBack(" 退出失败");
                    }
                }
            });
            //跳转到设备详情
            ((GetTopWebView) webview).registerHandler("skipToDeviceDetail", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        if (!StringUtils.isEmpty(data)) {
                            BannerModel bannerModel = new BannerModel();
                            bannerModel.setActionType("detail");
                            bannerModel.setActionValue(data);
                            WebActivity.this.setClickAction(bannerModel);
                            function.onCallBack(" 修改成功");
                        } else {
                            function.onCallBack(" data不能为空");
                        }
                    } catch (Exception e) {
                        function.onCallBack(" 修改失败");
                    }
                }
            });
            //注册跳转方法
            ((GetTopWebView) webview).registerHandler("skipTo", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        BannerModel bannerModel = JSONUtil.jsonObjectToBean(new JSONObject(data), BannerModel.class);
                        WebActivity.this.setClickAction(bannerModel);
                        function.onCallBack(" 跳转成功");
                    } catch (Exception e) {
                        function.onCallBack(" 跳转失败");
                    }
                }
            });
            //注册刷新方法
            ((GetTopWebView) webview).registerHandler("refreshCurrentPage", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        webview.reload();
                    } catch (Exception e) {
                        function.onCallBack(" 跳转失败");
                    }
                }
            });
            //注册开启加载动画方法
            ((GetTopWebView) webview).registerHandler("startLoadAnim", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        include_progress_bar.setVisibility(View.VISIBLE);
                    } catch (Exception e) {
                        function.onCallBack(" 跳转失败");
                    }
                }
            });
            //注册关闭加载动画方法
            ((GetTopWebView) webview).registerHandler("stopLoadAnim", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        include_progress_bar.setVisibility(View.GONE);
                    } catch (Exception e) {
                        function.onCallBack(" 跳转失败");
                    }
                }
            });
            //注册关闭加载动画方法
            ((GetTopWebView) webview).registerHandler("openCheckDialog", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        checkDialog = DialogUtils.createSureAndCancelDialog(WebActivity.this, data, "取消", "确认", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (null != checkDialog) {
                                    checkDialog.dismiss();
                                }
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (null != checkDialog) {
                                    checkDialog.dismiss();
                                }
                                webview.loadUrl("javascript:sureAction()");
                            }
                        });
                        checkDialog.show();
                    } catch (Exception e) {
                        function.onCallBack(" 跳转失败");
                    }
                }
            });
        }
    }

    private void initSubmitPicView() {
        List<String> strList = new ArrayList<>();
        strList.add("拍照");
        strList.add("本地相册");
        strList.add("取消");
        popupWindow = DialogUtils.createListPopupWindow(this, (ViewGroup) findViewById(R.id.rl_web), strList, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                switch (position) {
                    case 0:
                        skipToPhote();
                        break;
                    case 1:
                        skipToLocalImages();
                        break;
                    default:
                        break;
                }
            }
        });
        webview.postDelayed(new Runnable() {
            @Override
            public void run() {
                DialogUtils.darkenBackground(0.4f, WebActivity.this);
                popupWindow.showAtLocation((ViewGroup) findViewById(R.id.rl_web), Gravity.BOTTOM, 0, 0);
            }
        }, 1000);

    }

    private void skipToLocalImages() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_OPEN);
    }

    private void skipToPhote() {
        //只是加了一个uri作为地址传入
        File photoFile = createImgFile();
        if (null == photoFile) {
            ToastUtils.showToast(this, "本机不支持该功能，请从相册上传图片");
            return;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        photoUri = Uri.fromFile(photoFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(intent, PHOTO_OPEN);
    }


    /**
     * 自定义图片名，获取照片的file
     */
    private File createImgFile() {
        //确定文件名
        String fileName = "img_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";
        File dir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = Environment.getExternalStorageDirectory();
        } else {
            dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile = new File(dir, fileName);
        try {
            if (tempFile.exists()) {
                tempFile.delete();
            }
            if (!tempFile.createNewFile()) {
                ToastUtils.showToast(this, "本机不支持该功能，请从相册上传图片");
            }
        } catch (IOException e) {
            return null;
        }

        return tempFile;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE_OPEN:
                    Uri uri = data.getData();
                    dealWithAddImageAction(uri);
                    break;
                case PHOTO_OPEN:
                    dealWithAddImageAction(photoUri);
                    break;
                default:
                    break;
            }
        }

    }

    private void dealWithAddImageAction(Uri uri) {
        if (null != uri) {
            try {
                String path = FileUtil.getAbsolutePath(this, uri);
                if (StringUtils.isEmpty(path)) {
                    return;
                }

                File file;
                int totalCount = 0;
                do {
                    file = new File(path);
                    if (0 == file.length()) {
                        Thread.sleep(1000);
                        totalCount++;
                    }
                } while (0 == file.length() && totalCount < 8);

                if (null != file && 0 == file.length()) {
                    ToastUtils.showToast(this, "亲，你选择的图片太大了，我承受不起。");
                    return;
                }

                if ((file.length() / (1024 * 1024)) > 10) {
                    ToastUtils.showToast(this, "亲，你选择的图片太大了，我承受不起。");
                    return;
                }
                dealWithAddedImage(path);
            } catch (Exception e) {

            }
        }
    }

    /**
     * 启动压缩
     *
     * @param path
     */
    private void dealWithAddedImage(final String path) {
        try {
            Luban.with(this)
                    .load(new File(path)) //传入要压缩的图片
                    .setCompressListener(new OnCompressListener() { //设置回调

                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        }

                        @Override
                        public void onSuccess(final File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件
                            try {
                                if (null != webview) {
                                    webview.loadUrl("JavaScript:picDo(\"" + AndroidFileUtil.file2Base64String(file) + "\",\"" + faultId + "\")");
                                }
                                //initHttpHelper(AndroidFileUtil.file2Base64String(file));
                            } catch (Exception e) {
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过去出现问题时调用
                            ToastUtils.showToast(WebActivity.this, e.getMessage());
                        }
                    }).launch();
        } catch (Exception e) {
        }
    }

    private void initHttpHelper(String bitmap) {
//        HashMap<String, String> url_params = new HashMap<>();
//        url_params.put("imgbase64", bitmap);
//        if (!StringUtils.isEmpty(faultId)) {
//            url_params.put("faultId", faultId);
//        }
//        SubmitImgHttpHelper submitImgHttpHelper = new SubmitImgHttpHelper(this, Url.getGetUrl(this,Url.SUBMIT_PICTURE, null), SUBMIT_IMAGE_WHAT, handler, true, url_params);
//        submitImgHttpHelper.setParseJsonData(new SubmitImgParseJsonData());
//        submitImgHttpHelper.getHttpRequest();
//        ToastUtils.showToast(this, "图片上传中");
    }


    class SubmitImgHttpHelper extends HttpHelper {
        public SubmitImgHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> url_params) {
            super(activity, url, what, handler, isPost, url_params);
        }
    }

    protected class SubmitImgParseJsonData extends ParseJsonData {

        public SubmitImgParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            switch (what) {
                case SUBMIT_IMAGE_WHAT:
//                    if (StringUtils.isEmpty(objectData.toString()) || "{}".equals(objectData.toString())) {
//                        bundle.putBoolean(REQUEST_OK, true);
//                    } else {
//                        bundle.putBoolean(REQUEST_OK, false);
//                        bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
//                    }
                    break;
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))) {
            if (!StringUtils.isEmpty(bundle.getString(ParseJsonData.ERROR_MSG))) {
                //ToastUtils.showToast(this, bundle.getString(ParseJsonData.ERROR_MSG));
            } else if (msg.what == SUBMIT_IMAGE_WHAT) {
                ToastUtils.showToast(this, "图片上传失败");
            }
            return;

        }
        switch (msg.what) {
            case SUBMIT_IMAGE_WHAT:
                if (null != webview) {
                    webview.reload();
                }
                ToastUtils.showToast(this, "图片上传成功");
                break;
        }
    }

    @Override
    public void onSwipeRefresh() {
        swipeLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(false);
                if (!StringUtils.isEmpty(url)) {
                    webview.loadUrl(url);
                }
            }
        }, 2000);
    }


    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    @Override
    public void onBackPressed() {
        if (null != webview) {
            if (webview.canGoBack()) {
                webview.goBack();
                return;
            }
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobPush.setBadgeCounts(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        DialogUtils.closePopUpWindow(popupWindow);
        DialogUtils.closeDialog(checkDialog);
    }

}
